let express = require('express');
let router = express.Router();
let query=  require('./pool');
function isPoneAvailable(str) {
    var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(str)) {
        return false;
    } else {
        return true;
    }
}
//query user information
router.post('/queryUserInfo', function(req, res, next) {
	var obj={"result":"success","count":1,"data":null};
	//
	var openId=req.body.openid;
	//
	if(!openId){
		obj.result='failure';
		obj.count=0;
		obj.info = '参数错误';
		res.set('Content-Type','application/json');
		res.send(JSON.stringify(obj));
		return;
	}	
	//
 
		var mysql      = require('mysql');
		var connection = mysql.createConnection({
		  host     : '47.96.159.157',
		  user     : 'root',
		  password : 'jN+100][',
		  database : 'ksAppDB',
		  port:'3306'
		});

		connection.connect();

		connection.query('SELECT * FROM `User` WHERE openId=\''+openId+'\';', function (error, results, fields) {
		  console.log(results[0]);
		  if(!results[0]){
		  	obj.result='failure';
			obj.count=0;
			obj.info = '查无此人';
			res.set('Content-Type','application/json');
			res.send(JSON.stringify(obj));
			return;
		  }
		  var dataMode = {};
		  dataMode.userId = results[0].user_id;
		  dataMode.openId = results[0].openId;
		  dataMode.realName = results[0].real_name;
		  dataMode.nickName = results[0].nick_name;
		  dataMode.mobileNumber = results[0].mobile_number;
		  dataMode.modifyTime = results[0].gmt_modified;
		  //
		  obj.data = dataMode;
		  res.set('Content-Type','application/json');
		  res.send(JSON.stringify(obj));
		});

		connection.end();
		return;
 
});
//update user infomation
var selectUserSQL="SELECT `user_id`, `openId`, `user_type`, `real_name`, `nick_name`, `mobile_number`, `gmt_modified` FROM `User` WHERE openId= '#openId#' ";
var insertUserSQL="INSERT INTO `ksAppDB`.`User` (`openId`, `user_type`, `real_name`, `nick_name`, `mobile_number`) VALUES ('#openId#', 'user', '#real_name#', '#nick_name#', '#mobile_number#');\n";
var updateUserSQL="UPDATE `ksAppDB`.`User` SET `real_name`='#real_name#', `nick_name`='#nick_name#', `mobile_number`='#mobile_number#', `gmt_modified`=now() WHERE (`openId`='#openId#');\n";
router.post('/updateUserInfo', async (req, res) =>  {
    res.set('Content-Type','application/json');
	//参数处理
    var openid=req.body.openId;
    var mobileNumber=req.body.mobileNumber;
    var realName=req.body.realName;
    var nickName=req.body.nickName;
    console.log("传入参数="+JSON.stringify(req.body));
    //var isPoneFlag=isPoneAvailable(req.body.mobileNumber);
    var obj={"result":"success","count":1,"data":null};

    let queryResult = await query(selectUserSQL.replace("#openId#",openid));
    console.log(JSON.stringify(queryResult));
    if(queryResult.length<1){//插入
        let insertSQL = insertUserSQL.replace("#openId#",openid)
                    .replace("#real_name#",realName)
                    .replace("#nick_name#",nickName)
                    .replace("#mobile_number#",mobileNumber);
        let insertResult = await query(insertSQL);
        obj.data=insertResult;
	}else{//更新

	}


    res.set('Content-Type','application/json');
 	res.send(JSON.stringify(obj));
});

// router.post('/updateUserInfo', function(req, res, next) {
//     res.set('Content-Type','application/json');
// 	//参数处理
//     var openid=req.body.openId;
//     var mobileNumber=req.body.mobileNumber;
//     var realName=req.body.realName;
//     var nickName=req.body.nickName;
//     console.log("传入参数="+JSON.stringify(req.body));
//     //var isPoneFlag=isPoneAvailable(req.body.mobileNumber);
//     var obj={"result":"success","count":1,"data":null};
//
//     let rows = await query(selectUserSQL.replace("#openId#",openid));
//     console.log(JSON.stringify(rows));
// 	//查询是否存在
//     pool.getConnection(function(err,conn){
//         if(err){
//             //do something
//         }//end if
//
//         conn.query(selectUserSQL.replace("#openId#",openid),function(err,results){
//             if(err) return ;
//             if(results[0]==undefined){
//             	//插入新数据
// 				var insertSQL=insertUserSQL.replace("#openId#",openid)
//                     .replace("#real_name#",realName)
//                     .replace("#nick_name#",nickName)
//                     .replace("#mobile_number#",mobileNumber);
//                 conn.query(insertSQL,function(err,results){
//                     if(err) return ;
//                     console.log("插入新数据");
// 					console.log(JSON.stringify(results));
//                     obj.data=results.insertId;
//                     obj.info="插入成功";
//                     conn.release(); //释放连接
//                 });//end query
// 				//end 插入
// 			}else{
//             	//更新新数据
//                 var updateSQL=updateUserSQL.replace("#openId#",openid)
//                     .replace("#real_name#",realName)
//                     .replace("#nick_name#",nickName)
//                     .replace("#mobile_number#",mobileNumber);
//                 conn.query(updateSQL,function(err,results){
//                     if(err) return ;
//                     console.log("更新新数据");
//                     console.log(JSON.stringify(results));
//                     obj.data=results.insertId;
//                     obj.info="更新成功";
//                     conn.release(); //释放连接
//                 });//end query
// 				//end 更新
// 			}
//          });//end query
//     });//end pool
//
//
//     res.set('Content-Type','application/json');
//  	res.send(JSON.stringify(obj));
// });

module.exports = router;